package com.kuzan.autocloud.secutiry.controller;

import com.kuzan.autocloud.common.Result;
import com.kuzan.autocloud.secutiry.AccountVerifyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>Description: </p>
 *
 * @author kuzank
 */
@RestController
@RequestMapping({"/auth"})
public class AuthController {

    @Autowired
    private AccountVerifyService accountVerifyService;

    @Value("${token.expire.time}")
    private long tokenExpireTime;
    @Value("${refresh.token.expire.time}")
    private long refreshTokenExpireTime;
    @Value("${jwt.refresh.token.key.format}")
    private String jwtRefreshTokenKeyFormat;
    @Value("${jwt.blacklist.key.format}")
    private String jwtBlacklistKeyFormat;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 账号密码登录授权
     *
     * @return
     */
    @PostMapping("/account")
    public Result<Map<String, Object>> account(@RequestBody Map<String, String> Param) {

        return accountVerifyService.verify(Param);
    }

    /**
     * 刷新JWT
     *
     * @param refreshToken
     * @return
     */
    @GetMapping("/token/refresh")
    public Map<String, Object> refreshToken(@RequestParam String refreshToken) {

        Map<String, Object> resultMap = new HashMap<>();
        String refreshTokenKey = String.format(jwtRefreshTokenKeyFormat, refreshToken);
        String userName = (String) stringRedisTemplate.opsForHash().get(refreshTokenKey,
                "userName");
        if (StringUtils.isBlank(userName)) {
            resultMap.put("code", "10001");
            resultMap.put("msg", "refreshToken过期");
            return resultMap;
        }
        String newToken = ""; //buildJWT(userName);
        // 替换当前token，并将旧token添加到黑名单
        String oldToken = (String) stringRedisTemplate.opsForHash().get(refreshTokenKey, "token");
        stringRedisTemplate.opsForHash().put(refreshTokenKey, "token", newToken);
        stringRedisTemplate.opsForValue().set(String.format(jwtBlacklistKeyFormat, oldToken), "", tokenExpireTime, TimeUnit.MILLISECONDS);
        resultMap.put("code", "10000");
        resultMap.put("data", newToken);
        return resultMap;
    }


}
